package com.invengo.library_orionstar;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;

import com.ainirobot.coreservice.client.ApiListener;
import com.ainirobot.coreservice.client.RobotApi;
import com.ainirobot.coreservice.client.listener.TextListener;
import com.ainirobot.coreservice.client.module.ModuleCallbackApi;
import com.ainirobot.coreservice.client.speech.SkillApi;
import com.ainirobot.coreservice.client.speech.entity.TTSEntity;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.http.interceptor.logging.LocalLogUtil;
import me.goldze.mvvmhabit.utils.KLog;

public class RobotManager {
    private static RobotManager instance;

    private HandlerThread mApiCallbackThread;
    private ModuleCallbackApi mModuleCallback;
    private SkillApi mSkillApi;

    private SpeechCallback mSpeechCallback;

    private RobotManager() {
        mSpeechCallback = new SpeechCallback();
        mModuleCallback = new ModuleCallback();
        mApiCallbackThread = new HandlerThread("Invengo_Thread");
        mApiCallbackThread.start();
        initTipInterval();
        Messenger.getDefault().send(SpeechEvent.answer("没啥事，我就回去工作了"), "SPEECH_TO_PAGE");
    }

    public static RobotManager getInstance() {
        if (instance == null) {
            synchronized (RobotManager.class) {
                if (instance == null)
                    instance = new RobotManager();
            }
        }
        return instance;
    }


    private int tipSize = 0;
    private int closeSize = 0;

    private int workSize = 6;

    private void initTipInterval() {
        Observable.interval(5000, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    // TODO: 2024/4/18
                    if (--workSize > 0) {
                        return;
                    }

                    tipSize++;
                    if (tipSize > 3) {
                        tipSize = 0;
                        closeSize++;
                        if (closeSize > tips.size()) {
                            closeSize = 0;
                            Messenger.getDefault().send(SpeechEvent.answer("没啥事，我就回去工作了"), "SPEECH_TO_PAGE");
                            Observable.timer(3000, TimeUnit.MILLISECONDS)
                                    .subscribe(aLong1 -> Messenger.getDefault().send(ActionEvent.opHome(), "OPEARTION_TO_PAGE"));
                        } else {
                            int count = new Long(aLong).intValue();
                            Messenger.getDefault().send(SpeechEvent.answer(tips.get(count % tips.size())), "SPEECH_TO_PAGE");
                        }
                    }
                });
    }

    public void changeTip(List<String> tips) {
        this.tips = tips;
    }

    private List<String> tips = RobotConstant.TIP_SEARCH;


    public void refreshTip() {
        tipSize = 0;
    }

    /**
     * 初始化参数。。
     */
//    AbsRobotMessenger messenger = new AbsRobotMessenger() {
//        @Override
//        public void onRobotMessage(@Nullable String result) {
//            KLog.e("===>::" + result);
//            JSONObject jsonObject = JSON.parseObject(result);
//            String intent = jsonObject.getString("intent");
//            switch (intent) {
//                case "invengo_library&search_book":
//                    Messenger.getDefault().send("/robot/Search", "LAUNCH_PAGE");
//                    break;
//                case "invengo_library&search_popular":
//                    Messenger.getDefault().send("/robot/Popular", "LAUNCH_PAGE");
//                    break;
//                case "invengo_library&search_activity":
//                    Messenger.getDefault().send("/robot/Advert", "LAUNCH_PAGE");
//                    break;
//            }
//        }
//    };
    public void connectRobot(Application application) {
//        RobotMessengerManager.INSTANCE.connectRobot(application, () -> {
//            KLog.e("设备连接成功");
//            RobotMessengerManager.INSTANCE.setRobotMessenger(new MRobotMessenger((Context) application));
//        });
        connectServer(application);
    }


    public void connectServer(Application application) {
        RobotApi.getInstance().connectServer(application, new ApiListener() {
            @Override
            public void handleApiDisabled() {
                KLog.e("Api关闭");
            }

            /**
             * Server已连接，设置接收请求的回调，包含语音指令、系统事件等
             * 启动与RobotOS连接，这里可以做一些初始化的工作 例如连接语音,本地服务等
             */
            @Override
            public void handleApiConnected() {
                KLog.e("服务链接成功");
//                LocalLogUtil.temp2File("链接服务成功");
                RobotApi.getInstance().setCallback(mModuleCallback);
                RobotApi.getInstance().setResponseThread(mApiCallbackThread);
                initSkillApi(application);
            }

            @Override
            public void handleApiDisconnected() {
                LocalLogUtil.temp2File("丢失链接。。。。");
            }
        });
    }

    private void initSkillApi(Application application) {
        if (mSkillApi == null)
            mSkillApi = new SkillApi();
        mSkillApi.addApiEventListener(new ApiListener() {
            @Override
            public void handleApiDisabled() {

            }

            @Override
            public void handleApiConnected() {
                KLog.e("链接语音成功3333");
                mSkillApi.registerCallBack(mSpeechCallback);
                SkillApiHelper.setSkillApi(mSkillApi);
                SkillApiHelper.startApp();
            }

            @Override
            public void handleApiDisconnected() {

            }
        });
        mSkillApi.connectApi(application);
    }

    private TextListener speechListener = new TextListener() {
        @Override
        public void onStart() {
            isSpeaking = true;
            super.onStart();
        }

        @Override
        public void onStop() {
            isSpeaking = false;
            super.onStop();
        }

    };
    private boolean isSpeaking = false;

    public boolean isSpeaking() {
        return isSpeaking;
    }

    public void playText(String content) {
        if (mSkillApi != null)
            mSkillApi.playText(new TTSEntity("sid-1234567890", content), speechListener);
    }


    public void stopTTS() {
        if (mSkillApi != null)
            mSkillApi.stopTTS();
    }

    private boolean isSearch = false;

    public void setSearch(boolean search) {
        isSearch = search;
    }

    public boolean isSearch() {
        return isSearch;
    }


}
